package example

import grails.gorm.multitenancy.CurrentTenant
import org.grails.orm.hibernate.HibernateDatastore

@CurrentTenant(datastore = HibernateDatastore)
class VehicleController {

    static allowedMethods = [save: 'POST', update: 'PUT', delete: 'DELETE']

    def index(Integer max) {
        params.max = Math.min(max ?: 10, 100)
        params.fetch = [engines: 'join']
        respond Vehicle.list(params), model: [vehicleCount: Vehicle.count()]
    }

    def create() {
        respond new Vehicle(params)
    }

    def save(String model, Integer year) {
        def vehicle

        Vehicle.withTransaction {
            vehicle = new Vehicle(model: model, year: year)
            vehicle.save(flush: true)
        }

        if (vehicle.hasErrors()) {
            respond vehicle.errors, view: 'create'
        } else {
            flash.message = 'Vehicle created'
            redirect vehicle
        }
    }

    def show(Long id) {
        def vehicle = id ? Vehicle.findById(id, [fetch: [engines: 'join']]) : null
        respond vehicle
    }
}
